<template>
	<view class="addAddress  _width">
		<view class="card  _width">
			<u--form labelPosition="top" :model="form" ref="uFormRef" labelWidth="150">
				<u-form-item label="收货人">
					<u--input v-model="form.consignee" placeholder="请输入收货人姓名" clearable maxlength="20"
						@blur="validateConsignee"></u--input>
				</u-form-item>
				<u-form-item label="手机号" type="number" ref="item1">
					<u--input v-model="form.mobile" placeholder="请输入收货人电话" clearable maxlength="11" type="number"
						@blur="validateMobile"></u--input>
				</u-form-item>
			</u--form>
		</view>

		<view class="card address _width">
			<view class="col1 _width flex">
				<view class="left">
					<text class="label _width">地区</text>
				</view>

				<view class="right" @tap="changeSelectMap">
					<text class="text1" v-if="locationName==''">
						请选择地区
					</text>
					<text class="text2" v-show="locationName!=''">
						{{locationName}}
					</text>

					<view class="icon">
						<image src="https://img.zhizhuangtong.com/project_media/img/xcx/addres.png" />
					</view>
				</view>

			</view>

			<view class="col2 _width flex">
				<view class="left">
					<text class="label _width">地址</text>
				</view>
				<view class="right">
					<text class="placeholder" v-if="locationName==''" @click="onAddress">街道、门牌号等地址信息</text>
					<up-textarea v-model="form.address" placeholder="" clearable maxlength="200"
						@blur="saveLatestAddress" v-if="locationName!=''"></up-textarea>
				</view>
			</view>
		</view>


		<view class="card default _width">
			<view class="left">
				<text class="label _width">设为默认地址</text>
				<text class="tips _width">提醒：下单时会优先使用该地址</text>
			</view>

			<view class="right">
				<radio value="1" :checked="form.default" @click="defaultClick" />
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottomFexBtn">
			<view class="rowConter">

				<view class="row">
					<view class="btn" @click="save">
						确认
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		defineExpose,
		watch
	} from 'vue';
	import {
		onLoad,
		onReady,
		onShow,
		onHide,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		mapGetInfo,
	} from '@/api/require.js'
	import {
		addAddress,
		edit,
		getAddress
	} from '@/api/order.js'
	const params = ref({
		id: null,
	});

	const selected = ref(false) //设置默认地址


	const form = ref({
		id: '',
		consignee: '', //收货人
		mobile: '', //手机号
		tel: '', //固定电话
		default: 0, //默认地址:0=否,1=是  
		province: '', //省code  
		city: '', //市 
		county: '', //区code  
		address: '', //详细地址  
		location: '',
	})


	//获取经纬度信息
	const location = ref('')
	const locationName = ref('')
	const locationInfo = ref('') //地址信息


	onMounted(() => {
		uni.setStorageSync('isSave', 0)
		uni.setStorageSync('location', '')
		uni.setStorageSync('locationName', '')
		location.value = ''
		locationName.value = ''
		locationInfo.value = ''
	})

	onReady(() => {
		uni.setStorageSync('location', '')
		uni.setStorageSync('locationName', '')
		location.value = ''
		locationName.value = ''
		locationInfo.value = ''
	})
	onLoad((option) => {
		if (option.id) {
			form.value.id = option.id;
		}
		if (option.type === 'edit') {
			uni.setNavigationBarTitle({
				title: '修改收货地址',
			});
		} else {
			uni.setNavigationBarTitle({
				title: '新增收货地址',
			});
		}
	});

	onShow(() => {
		if (form.value.id) {
			addresDetails(form.value.id); //地址详情回显
		}
		// console.log(uni.getStorageSync('location'))
		location.value = uni.getStorageSync('location') || ''
		const isSave = uni.getStorageSync('isSave')
		console.log('isSaveisSaveisSaveisSaveisSave', isSave)
		if (isSave == 1) {
			console.log('选择地址～～～～～～～')
			uni.setStorageSync('address', '')
			// form.value.address = ''
			form.value.location = location.value
			getLocalInfo()

		} else {
			const address = uni.getStorageSync('address')
			form.value.address = address
			console.log('非选择地址')
			// getLocalInfo()
		}

		// if (location.value != '') {
		// 	getLocalInfo()
		// }
	})

	// 地址详情回显
	const addresDetails = async (id) => {
		const params = {
			id: id
		}
		const res = await getAddress(params)
		if (res.code == 1) {
			console.log('resresres', res)
			form.value.consignee = res.data.address.consignee;
			form.value.mobile = res.data.address.mobile;
			// form.value.location = res.data.address.location
			form.value.default = res.data.address.default === 1 ? 1 : 0; // 切换状态
			locationName.value = res.data.address.province_name + res.data.address.city_name + res.data.address
				.county_name;
			form.value.location = locationName.value;
			form.value.address = res.data.address.address;
			form.value.province = res.data.address.province;
			form.value.county = res.data.address.county;
			form.value.city = res.data.address.city;
			form.value.address = res.data.address.address
		} else {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: res.msg
			// });
		}
	}


	//获得地址相关信息
	const getLocalInfo = async () => {
		let obj
		obj = {
			location: location.value,
			// get_design_num: '1'
		}
		const res = await mapGetInfo(obj)
		if (res.code == 1) {
			locationInfo.value = res.data.res;
			form.value.province = res.data.res.province;
			form.value.city = res.data.res.city;
			form.value.county = res.data.res.county;

			form.value.location = location.value;
			// locationName.value = res.data.res.province_name + res.data.res.city_name + res.data.res.county_name +
			// 	res.data.res.address;
			locationName.value = res.data.res.province_name + res.data.res.city_name + res.data.res.county_name;

			// form.value.address = res.data.res.province_name + res.data.res.city_name + res.data.res.county_name +
			// 	res.data.res.address;

			form.value.address = res.data.res.address;
			uni.setStorageSync('address', form.value.address)
			const isSave = uni.getStorageSync('isSave')

			// if(isSave ===1){
			// 	console.log('1111')
			// 	// 重新选择了地区
			// 	// form.value.address  = res.data.res.address;
			// 	form.value.address = ''
			// }else{
			// 	console.log('22222')
			// 	// 没有重新选择地区
			// 	form.value.address = res.data.res.address
			// }
			// uni.setStorageSync('address', form.value.address)

		} else {
			locationInfo.value = '';
			form.value.province = '';
			form.value.city = '';
			form.value.county = '';
			form.value.address = '';
			form.value.location = '';
		}
	}


	// 手动修改了地址
	const saveLatestAddress = (val) => {
		uni.setStorageSync('isSave', 0)
		uni.setStorageSync('address', val.detail.value)
		form.value.address = val.detail.value
	}


	// 选择地址
	const changeSelectMap = () => {
		uni.setStorageSync('isSave', 0)
		uni.setStorageSync('address', form.value.address)
		uni.navigateTo({
			url: '/pages/requireB/map/index'
		})
	}

	// 请先选择地址
	const onAddress = async () => {
		uni.showToast({
			icon: 'none',
			title: '请先选择地区'
		});
	}

	// 设置默认地址
	const defaultClick = async () => {
		form.value.default = form.value.default === 1 ? 0 : 1; // 切换状态
		// form.value.default = form.value.default === 1 ? true : false; // 切换状态
	};



	const showToast = (message) => {
		uni.showToast({
			icon: 'none',
			title: message
		});
	};

	const validateForm = () => {
		if (!form.value.consignee) return '请填写收货人';
		if (!form.value.mobile) return '请填写收货人手机号';
		if (!form.value.location) return '请选中地区';
		if (!form.value.address) return '请填写地址';
		return null;
	};

	// 验证收货人姓名
	// 验证收货人姓名
	const validateConsignee = () => {
		const regex = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/; // 允许汉字、字母、数字
		if (!regex.test(form.value.consignee)) {
			showToast('收货人姓名只能包含汉字、字母和数字，不能包含空格或特殊符号');
			form.value.consignee = '';
		}
	};


	// 验证手机号
	const validateMobile = () => {
		const regex = /^1[3-9]\d{9}$/;
		if (!regex.test(form.value.mobile)) {
			showToast('请输入有效的手机号');
			form.value.mobile = '';
		}
	};

	// 保存地址
	const save = async () => {
		const validationMessage = validateForm();
		if (validationMessage) {
			showToast(validationMessage);
			return;
		}
		const apiCall = form.value.id ? edit : addAddress;
		const successMessage = form.value.id ? '修改成功' : '添加成功';
		const errorMessage = form.value.id ? '修改失败' : '添加失败';

		try {
			const res = await apiCall(form.value);
			if (res.code === 1) {
				showToast(successMessage);
				setTimeout(() => {
					uni.$emit('refreshIfNeeded', true);
					// uni.navigateBack();
					uni.navigateBack({
						delta: 1
					})
				}, 1000);
			} else {
				showToast(res.msg || errorMessage);
			}
		} catch (error) {
			showToast('操作失败，请稍后再试');
		}
	};

	onUnload(() => {
		console.log('删除数据')
		uni.setStorageSync('isSave', 0)
		uni.setStorageSync('location', '')
		uni.setStorageSync('locationName', '')
		location.value = ''
		locationName.value = ''
		locationInfo.value = '';
		// form.value.province = '';
		// form.value.city = '';
		// form.value.county = '';
		form.value.address = '';
		form.value.location = '';
	})
</script>

<style lang="less" scoped>
	.addAddress {
		min-height: 100vh;
		// border: 1px solid red;
		padding-top: 20rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-bottom: calc(150rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(150rpx + env(safe-area-inset-bottom));
		box-sizing: border-box;
		flex-wrap: wrap;


		.card {
			flex-wrap: wrap;
			background: #FFFFFF;
			border-radius: 18rpx;
			margin-bottom: 20rpx;
			padding: 0 20rpx;
			// box-shadow: 0 5rpx 8rpx 0 rgba(0, 0, 0, .08);
			box-sizing: border-box;

			&:last-child {
				margin-bottom: 0;
			}

			::v-deep .u-form-item {
				width: 100%;
				he display: flex;
				flex-wrap: wrap;
				border-bottom: 1rpx solid #E0E0E0;

				&:last-child {
					border-bottom: none !important;
				}

				.u-form-item__body__right__message {
					text-align: right;
					padding-right: 20rpx;
					padding-bottom: 10rpx;
					box-sizing: border-box;
				}

				.u-form-item__body {
					display: flex;
					flex-direction: row !important;
					padding: 0 !important;
					box-sizing: border-box;


					.u-form-item__body__left {
						height: 90rpx;
						margin-bottom: 0 !important;

						.u-form-item__body__left__content__required {
							left: 0 !important;
						}

						.u-form-item__body__left__content__label {
							padding-left: 0rpx;
						}
					}

					.u-form-item__body__right {
						display: flex;
						height: 90rpx;

						.u-form-item__body__right__content__slot {
							display: flex;

							.u-input {
								border: none !important;
							}

							.u-input__content__field-wrapper {
								input {
									text-align: right !important;
								}

								input-placeholde {
									color: red ! !important;
								}
							}


						}


					}
				}
			}


		}


		// 地址
		.address {
			.col1 {
				display: flex;
				border-bottom: 1rpx solid #E0E0E0;
				padding: 25rpx 0;
				box-sizing: border-box;

				.left {
					width: 100rpx;

					.label {
						display: block;
						height: 100%;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #333333;
						font-style: normal;
						text-transform: none;
					}

				}

				.right {
					// width: 100%;
					flex: 1;
					display: flex;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx !important;
					// line-height: 40rpx!important;
					text-align: right;
					font-style: normal;
					text-transform: none;

					.text1 {
						flex: 1;
						color: #C0C4CC !important;
					}

					.text2 {
						flex: 1;
						color: #333333 !important;
					}

					.icon {
						height: 100%;
						display: flex;
						align-items: flex-start;
						box-sizing: border-box;

						image {
							width: 34rpx;
							height: 33rpx;
							margin-top: 2rpx;
							margin-left: 20rpx;
						}
					}
				}




			}

			.col2 {
				padding: 30rpx 0;
				box-sizing: border-box;

				.left {
					width: 100rpx;

					.label {
						display: block;
						height: 100%;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #333333;
						font-style: normal;
						text-transform: none;
					}

				}

				.right {
					flex: 1;

					.placeholder {
						display: block;
						width: 100%;
						padding: 9rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx !important;
						color: #C0C4CC !important;
						text-align: right;
						font-style: normal;
						text-transform: none;
						border: 1rpx solid #E0E0E0;
						border-radius: 4px;
						height: 140rpx;
						box-sizing: border-box;
					}

					::v-deep .u-textarea {
						width: 100%;
						height: 240rpx;
						box-sizing: border-box;
						border: 1rpx solid #E0E0E0;

						textarea {
							word-wrap: break-word;
							word-break: break-all;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx !important;
							color: #333333 !important;
							line-height: 40rpx !important;
							height: 100% !important;
							text-align: left;
							font-style: normal;
							text-transform: none;
						}

					}
				}
			}



		}


		// 默认地址
		.default {
			display: flex;
			height: 150rpx;
			align-items: center;
			padding: 25rpx;
			box-sizing: border-box;

			.left {
				flex: 1;
				flex-wrap: wrap;

				.label {
					display: block;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 30rpx;
					color: #333333;
					line-height: 40rpx;
					text-align: left;
					font-style: normal;
					text-transform: none;
					margin-bottom: 10rpx;
				}

				.tips {
					display: block;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #999999;
					line-height: 40rpx;
					text-align: left;
					font-style: normal;
					text-transform: none;
				}

			}

			.right {
				display: flex;
				justify-content: center;

			}
		}


		.bottomFexBtn {
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 5;
			padding-bottom: env(safe-area-inset-bottom);
			padding-bottom: constant(safe-area-inset-bottom);
			height: calc(120rpx + env(safe-area-inset-bottom));
			height: calc(120rpx + constant(safe-area-inset-bottom));
			width: 100%;
			// background-color: #000000 !important;
			// backdrop-filter: blur(10px) !important;
			// background-color: rgba(255, 255, 255, .82) !important;
			// box-shadow: 0rpx -4rpx 6rpx 0rpx rgba(0, 0, 0, 0.05);
			box-sizing: border-box;
			display: flex;
			align-items: flex-start;

			.rowConter {
				padding: 15rpx 25rpx;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.row {
					width: 100%;
					display: flex;
					justify-content: center;
					align-items: center;

					.btn {
						width: 100%;
						height: 80rpx;
						background: linear-gradient(113deg, #F2BD6F 0%, #CCA05F 100%);
						border-radius: 20rpx;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 500;
						font-size: 32rpx;
						color: #FFFFFF;
						line-height: 80rpx;
						text-align: center;
						font-style: normal;
						text-transform: none;
					}


				}
			}
		}
	}
</style>